347. 前 K 个高频元素
为保证权益,题目请参考 347. 前 K 个高频元素(From LeetCode).
解决方案1
CPP
C++
/**
* 347.前 K 个高频元素
* @author KevenGe
* @date 2020-09-13
*/
#include <iostream>
#include <unordered_map>
#include <vector>
#include <queue>
using namespace std;
struct cmp {
bool operator()(pair<int, int> p1, pair<int, int> p2) {
return p1.second > p2.second;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int> &nums, int k) {
unordered_map<int, int> occurrences;
for (auto num:nums) {
occurrences[num]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pri;
for (auto x:occurrences) {
if (pri.size() < k) {
pri.push(x);
} else {
if (x.second > pri.top().second) {
pri.push(x);
pri.pop();
}
}
}
// get the answer
vector<int> ans;
while (!pri.empty()) {
ans.emplace_back(pri.top().first);
pri.pop();
}
return ans;
}
};
int main() {
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54